<template>
  <div class="h-[85%]">
    <div class="flex flex-row flex-wrap gap-x-[25px] w-1/1 mt-15px h-1/1" style="align-content: flex-start">
      <div v-show="fileList.length === 0" class="w-1/1" :image-size="100">
        <el-empty description="暂无数据" />
      </div>
      <div v-for="p in fileList" :key="p.id" class="w-[100px] h-[100px] mb-[50px]">
        <div class="w-1/1 h-[100px] bg-[#f0f0f0] relative" @click="chooseInList(p)">
          <div
            class="absolute flex flex-col justify-center w-[25px] h-[25px] rounded-1/2 bg-red-600 right-[5px] top-[5px] z-3"
            v-show="isChoose(p) !== -1"
          >
            <span class="text-[#fff] relative transform w-1/1 text-center inline-block text-[12px]">{{ isChoose(p) }}</span>
          </div>
          <el-image
            :class="[
              'w-1/1',
              'h-1/1',
              { 'border border-solid border-[2px] border-[#5fb878]': isChoose(p) !== -1 },
              'z-2',
              'relative'
            ]"
            :src="getOrigin(p.file_type) === 0 ? p.cover : p.origin_name"
            fit="scale-down"
          ></el-image>
          <div
            class="absolute w-[50px] h-[50px] z-3 top-1/2 left-1/2 transform translate-x-[-50%] translate-y-[-50%]"
            v-show="videoInClude.includes(p.file_type)"
          >
            <el-image src="./shipin1.png" class="w-1/1 h-1/1"></el-image>
          </div>
        </div>
        <el-popover
          trigger="click"
          placement="top"
          :width="getOrigin(p.file_type) === 0 ? 270 : 200"
          transition="none"
          :show-arrow="false"
          :offset="-0"
          :hide-after="0"
          v-model:visible="p.isShow"
        >
          <div class="flex justify-center">
            <el-button link type="primary" size="small" @click="p.isEdit = true">编辑</el-button>
            <el-button link type="primary" size="small" @click="preview(p)">查看</el-button>
            <el-button link type="primary" size="small" @click="deleteFileList([p.id])">删除</el-button>
            <el-button link type="primary" size="small" @click="CopyUrlToClipBroad(p.origin_name)">复制链接</el-button>
            <el-button link type="primary" size="small" v-if="getOrigin(p.file_type) === 0" @click="openCover(p)"
              >设置封面</el-button
            >
          </div>
          <template #reference>
            <div
              class="text-center w-1/1 cursor-default py-5px tips-out tips-in relative"
              v-if="!p.isEdit"
              :data-title="p.real_name"
            >
              <span class="overflow-hidden inline-block w-1/1 whitespace-nowrap overflow-ellipsis">{{ p.real_name }}</span>
            </div>
            <el-input
              @blur="editFileName(p)"
              v-model="p.real_name"
              v-else
              :input-style="{ height: '24px', fontSize: '14px' }"
            ></el-input>
          </template>
        </el-popover>
      </div>
    </div>
    <div class="flex flex-row justify-end">
      <el-pagination
        small
        layout="prev,pager,next"
        background
        :page-size="initParams.pageSize"
        :total="pageConfig.total"
        v-model:current-page="initParams.pageNum"
      ></el-pagination>
    </div>
    <viewer ref="viewRef"></viewer>
    <video-player ref="videoRef"></video-player>
    <set-cover ref="setCoverRef"></set-cover>
  </div>
</template>

<script setup lang="ts">
import { reactive, watch, ref } from "vue";
import { getFileList, edit, deleteFile, setCover as setCoverApi } from "@/api/modules/file";
import { useHandleData } from "@/hooks/useHandleData";
import { File } from "@/components/UploadCool/interface/index";
import { ElMessage } from "element-plus";
import setCover from "./components/setCover.vue";
import viewer from "./components/viewer.vue";
import videoPlayer from "./components/videoPlayer.vue";

// 打开封面设置
const setCoverRef = ref<InstanceType<typeof setCover> | null>();
const openCover = (p: File) => {
  p.isShow = false;
  const params: any = {
    row: p,
    api: setCoverApi,
    refresh: getList
  };
  setCoverRef.value?.open(params);
};

// 复制地址到到剪切板
const CopyUrlToClipBroad = (url: string) => {
  navigator.clipboard.writeText(url);
  ElMessage.success("成功复制链接的剪切板");
};

// 当前被选择的素材
const nowChooseList = ref<File[]>([]);

// 选中素材
const emits = defineEmits(["choose"]);
const chooseInList = (row: File) => {
  const index = nowChooseList.value.findIndex(e => e.id === row.id);
  if (index === -1) {
    if (props.maxSelect !== 0 && nowChooseList.value.length === props.maxSelect) {
      nowChooseList.value.shift();
      nowChooseList.value.push(row);
    } else {
      nowChooseList.value.push(row);
    }
  } else {
    nowChooseList.value.splice(index, 1);
  }
  emits("choose", nowChooseList.value);
};

// 判断是否在被选中
const isChoose = (row: File) => {
  return nowChooseList.value.findIndex((e: File) => e.id === row.id);
};

const videoInClude = ref(["video/mp4", "video/avi"]);
const imageInClude = ref(["image/jpg", "image/png", "image/jpeg", "image/gif", "image/webp"]);
const getOrigin = (file_type: string) => {
  if (videoInClude.value.includes(file_type)) {
    return 0;
  } else if (imageInClude.value.includes(file_type)) {
    return 1;
  } else {
    return 2;
  }
};

// 编辑文件名
const editFileName = async (row: File) => {
  row.isEdit = false;
  try {
    await edit({ id: row.id, real_name: row.real_name });
  } catch (error) {}
};

// 删除文件
const deleteFileList = async (ids: any) => {
  try {
    await useHandleData(deleteFile, { ids }, "删除所选内容");
    await getList();
  } catch (error) {}
};

// 当前pros
interface Props {
  pid?: number;
  fileType?: string; //文件类型
  maxSelect?: number; //最大选择数
  filename?: string;
}

const props = withDefaults(defineProps<Props>(), { pid: 1, fileType: "", maxSelect: 0, filename: "" });

const initParams = reactive({ pageSize: 50, pageNum: 1, file_type: props.fileType, filename: "" });
const pageConfig = reactive({ total: 0 });

const fileList = ref<File[]>([]);

const getList = async () => {
  const { data } = await getFileList({ dir_id: props.pid, ...initParams });
  fileList.value = (data as any).list.map((e: any) => {
    return { ...e, isEdit: false, isShow: false };
  });
  pageConfig.total = (data as any).total;
  nowChooseList.value = [];
};

watch(
  () => props.pid,
  async () => {
    getList();
  },
  { immediate: true }
);

watch(
  () => initParams,
  async () => {
    getList();
  },
  { deep: true }
);

watch(
  () => props.filename,
  async () => {
    initParams.filename = props.filename;
  }
);

// 图片预览
const viewRef = ref<InstanceType<typeof viewer> | null>();
const videoRef = ref<InstanceType<typeof videoPlayer> | null>();
const preview = (p: any) => {
  p.isShow = false;
  if (imageInClude.value.includes(p.file_type)) {
    viewRef.value?.open(p.origin_name);
  } else if (videoInClude.value.includes(p.file_type)) {
    videoRef.value?.acceptParams({ url: p.origin_name, cover: p.cover });
  }
};

defineExpose({ getList });
</script>

<style lang="scss" scoped>
.tips-in:hover::before {
  position: absolute;
  top: -25px;
  left: 50%;
  z-index: 10;
  padding: 3px 10px;
  font-size: 12px;
  color: #ffffff;
  white-space: nowrap;
  content: attr(data-title);
  background-color: #333333;
  border-radius: 10px;
  opacity: 0;
  transition: opacity 0.3s ease;
  transform: translateX(-50%);
}
.tips-out:hover::before {
  opacity: 1;
}
</style>
